<template>
  <el-dialog
    v-model="visible"
    :title="isEdit ? '编辑文章' : '新增文章'"
    width="1200px"
    destroy-on-close
    @close="handleClose"
  >
    <el-form ref="formRef" :model="form" :rules="rules" label-width="100px">
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="form.title" placeholder="请输入文章标题" />
      </el-form-item>
      
      <el-form-item label="文章分类" prop="categoryId">
        <el-select v-model="form.categoryId" placeholder="请选择分类" style="width: 100%">
          <el-option
            v-for="category in categories"
            :key="category.value"
            :label="category.label"
            :value="category.value"
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="文章标签" prop="tags">
        <el-select 
          v-model="form.tags" 
          multiple 
          filterable 
          remote 
          reserve-keyword 
          placeholder="请输入标签"
          remote-show-suffix 
          :remote-method="remoteMethod" 
          allow-create 
          default-first-option
          :loading="tagSelectLoading" 
          style="width: 100%"
        >
          <el-option 
            v-for="item in tagOptions" 
            :key="item.value" 
            :label="item.label" 
            :value="item.value" 
          />
        </el-select>
      </el-form-item>
      
      <el-form-item label="标题图片" prop="titleImage">
        <div style="display: flex; align-items: flex-start; gap: 20px;">
          <UploadComponent @upload-success="handleUploadSuccess" />
          <div v-if="form.titleImage" style="flex: 1;">
            <el-input v-model="form.titleImage" placeholder="图片URL" readonly />
            <div style="margin-top: 10px;">
              <el-button type="primary" size="small" @click="previewImage">预览图片</el-button>
            </div>
          </div>
        </div>
      </el-form-item>
      
      <el-form-item label="文章内容" prop="content">
        <MdEditor 
          v-model="form.content" 
          :height="400"
          :preview="true"
          :toolbars="toolbars"
          placeholder="请输入文章内容"
        />
      </el-form-item>
      
      <el-form-item label="文章摘要" prop="summary">
        <el-input
          v-model="form.summary"
          type="textarea"
          :rows="3"
          placeholder="请输入文章摘要"
        />
      </el-form-item>
      
      <el-form-item label="文章状态" prop="status">
        <el-radio-group v-model="form.status">
          <el-radio :label="1">发布</el-radio>
          <el-radio :label="0">草稿</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    
    <template #footer>
      <div class="dialog-footer">
        <el-button @click="handleClose">取消</el-button>
        <el-button type="primary" @click="handleSubmit">确定</el-button>
      </div>
    </template>
    
    <!-- 图片预览 -->
    <el-image-viewer
      v-if="previewVisible && form.titleImage"
      :url-list="[form.titleImage]"
      :initial-index="0"
      @close="previewVisible = false"
    />
  </el-dialog>
</template>

<script setup>
import { ref, reactive, watch } from 'vue'
import { ElMessage } from 'element-plus'
import MdEditor from 'md-editor-v3'
import 'md-editor-v3/lib/style.css'
import UploadComponent from '@/views/function/material/upload/index.vue'
import { publishArticle, updateArticle, getArticleDetail } from '@/service/api/blog/AdminCategoryController'
import { getCategorySelect } from '@/service/api/blog/classificationman'
import { selectTags, getTagSelect } from '@/service/api/blog/label'

const emit = defineEmits(['success'])

// 响应式数据
const visible = ref(false)
const isEdit = ref(false)
const previewVisible = ref(false)
const formRef = ref()
const tagSelectLoading = ref(false)

// 表单数据
const form = reactive({
  id: null,
  title: '',
  categoryId: null,
  titleImage: '',
  content: '',
  summary: '',
  status: 1,
  tags: []
})

// 分类和标签数据
const categories = ref([])
const tagOptions = ref([])

// 富文本编辑器工具栏配置
const toolbars = [
  'bold', 'underline', 'italic', 'strikeThrough', '-',
  'title', 'sub', 'sup', 'quote', 'unorderedList', 'orderedList', 'task', '-',
  'codeRow', 'code', 'link', 'image', 'table', 'mermaid', 'katex', '-',
  'revoke', 'next', 'save', '=', 'pageFullscreen', 'fullscreen', 'preview', 'htmlPreview', 'catalog'
]

// 表单验证规则
const rules = {
  title: [{ required: true, message: '请输入文章标题', trigger: 'blur' }],
  categoryId: [{ required: true, message: '请选择文章分类', trigger: 'change' }],
  content: [{ required: true, message: '请输入文章内容', trigger: 'blur' }],
  tags: [{ required: true, message: '请选择文章标签', trigger: 'blur' }]
}

// 处理上传成功
function handleUploadSuccess(url) {
  form.titleImage = url
}

// 预览图片
function previewImage() {
  if (form.titleImage) {
    previewVisible.value = true
  }
}

// 远程搜索标签
const remoteMethod = (query) => {
  if (query) {
    tagSelectLoading.value = true
    setTimeout(() => {
      tagSelectLoading.value = false
      selectTags(query).then((res) => {
        if (res.success) {
          tagOptions.value = res.data
        }
      })
    }, 200)
  }
}

// 打开对话框
function open(type, data = null, categoryList = []) {
  visible.value = true
  isEdit.value = type === 'edit'
  categories.value = categoryList
  
  // 加载标签数据
  loadTags()
  
  if (isEdit.value && data) {
    // 编辑模式，加载文章详情
    loadArticleDetail(data.id)
  } else {
    // 新增模式，重置表单
    resetForm()
  }
}

// 加载标签数据
async function loadTags() {
  try {
    const res = await getTagSelect()
    tagOptions.value = res.data || []
  } catch (error) {
    console.error('加载标签数据失败:', error)
  }
}

// 加载文章详情
async function loadArticleDetail(id) {
  try {
    const response = await getArticleDetail(id)
    if (response.success) {
      const article = response.data
      Object.assign(form, {
        id: article.id,
        title: article.title,
        categoryId: article.categoryId,
        titleImage: article.titleImage || '',
        content: article.content,
        summary: article.summary || '',
        status: article.status,
        tags: article.tagIds || []
      })
    }
  } catch (error) {
    ElMessage.error('加载文章详情失败')
  }
}

// 重置表单
function resetForm() {
  Object.assign(form, {
    id: null,
    title: '',
    categoryId: null,
    titleImage: '',
    content: '',
    summary: '',
    status: 1,
    tags: []
  })
  formRef.value?.clearValidate()
}

// 提交表单
async function handleSubmit() {
  try {
    await formRef.value.validate()
    
    const submitData = { ...form }
    
    if (isEdit.value) {
      await updateArticle(submitData)
      ElMessage.success('文章更新成功')
    } else {
      await publishArticle(submitData)
      ElMessage.success('文章发布成功')
    }
    
    emit('success')
    handleClose()
  } catch (error) {
    if (error !== false) {
      ElMessage.error(isEdit.value ? '文章更新失败' : '文章发布失败')
    }
  }
}

// 关闭对话框
function handleClose() {
  visible.value = false
  previewVisible.value = false
  resetForm()
}

// 暴露方法给父组件
defineExpose({
  open
})
</script>

<style scoped>
.w-full {
  width: 100%;
}

.my-header {
  display: flex;
  flex-direction: row;
  justify-content: space-between;
  align-items: center;
}
</style> 